package com.vint.leetcode;

import com.vint.common.TreeNode;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

//TODO:BFS/DFS
/*
 * 1. done
 * 2. easy
 * 3. tree, 递归
 * 将一棵树左右子树对调，镜面反射
 */
public class Leetcode226 {
    public TreeNode invertTree(TreeNode root) {
        if(null==root)return root;
        TreeNode left = root.left;
        root.left = invertTree(root.right);
        root.right = invertTree(left);
        return root;
    }

    //2
    public TreeNode invertTree2(TreeNode root) {

        if (root == null) {
            return null;
        }

        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        stack.push(root);

        while(!stack.isEmpty()) {
            final TreeNode node = stack.pop();
            final TreeNode left = node.left;
            node.left = node.right;
            node.right = left;

            if(node.left != null) {
                stack.push(node.left);
            }
            if(node.right != null) {
                stack.push(node.right);
            }
        }
        return root;
    }
    //3
    public TreeNode invertTree3(TreeNode root) {

        if (root == null) {
            return null;
        }

        final Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while(!queue.isEmpty()) {
            final TreeNode node = queue.poll();
            final TreeNode left = node.left;
            node.left = node.right;
            node.right = left;

            if(node.left != null) {
                queue.offer(node.left);
            }
            if(node.right != null) {
                queue.offer(node.right);
            }
        }
        return root;
    }
    public static void main(String[] args) {
        Leetcode226 leetcode100= new Leetcode226();
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.left.left = new TreeNode(5);
        root.right = new TreeNode(4);
        root.right.right= new TreeNode(2);
        TreeNode ret = leetcode100.invertTree(root);
        System.out.println("success!");
    }
  }
